import DB.DB;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class meetingJFrame extends JFrame {

    private static final String REFRESH = "select * from meeting limit 6;";

    private JLabel search, num, clear, selectAll, swi, map, top,bigGraph;
    private JLabel[] device;
    private JTextField searchText, numText, bigText;
    private ArrayList<MeetingRoom> meetingRooms, resultRooms;
    private Position currentPosition;
    private boolean isSwitchOn;
    private boolean[] deviceSelected;
    private JTable result;
    private JTable personNum;
    private MyTableModel tableModel;

    public meetingJFrame() {
        super("智能会议室管理系统");
        this.setSize(1200, 930);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        ImageIcon img = new ImageIcon("images/背景.png");//这是背景图片
        JLabel imgLabel = new JLabel(img);//将背景图放在标签里。
        this.getLayeredPane().add(imgLabel, new Integer(Integer.MIN_VALUE));//背景标签添加
        imgLabel.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());//设置背景标签的位置
        Container cp = this.getContentPane();
        cp.setLayout(null);
        ((JPanel) cp).setOpaque(false); //注意这里，将内容面板设为透明

        isSwitchOn = false;
        //设备默认不选中
        deviceSelected = new boolean[4];
        for (int i = 0; i < 4; i++) {
            deviceSelected[i] = false;
        }

        bigGraph = new JLabel(new ImageIcon("bigMaps/1号厅.png"));
        bigGraph.setBounds(0,305,1200,566);
        bigGraph.setName("10");
        bigGraph.setVisible(false);
        cp.add(bigGraph);

        searchText = new JTextField("输入所在房间编号");
        searchText.setBounds(230, 80, 460, 35);
        beautifyTextField(searchText);
//        searchText.setVisible(false);
        cp.add(searchText);

        numText = new JTextField("选择与会人数");
        numText.setBounds(800, 80, 200, 35);
        beautifyTextField(numText);
        numText.setForeground(Color.black);
        numText.setEditable(false);
        cp.add(numText);

        MyTableModel selectModel = new MyTableModel();
        selectModel.addColumn("");
        selectModel.addRow(new Object[]{"6"});
        selectModel.addRow(new Object[]{"8"});
        selectModel.addRow(new Object[]{"12"});
        selectModel.addRow(new Object[]{"24"});
        selectModel.addRow(new Object[]{"50"});
        personNum = new JTable(selectModel);
        beautifyTable(personNum);
        personNum.setRowHeight(30);
        personNum.setBounds(800, 115, 200, 150);
        personNum.setVisible(false);
        cp.add(personNum);

        search = new JLabel(new ImageIcon("images/搜索.png"));
        search.setBounds(170, 80, 600, 35);
        search.setName("4");
        cp.add(search);

        num = new JLabel(new ImageIcon("images/与会人数.png"));
        num.setBounds(800, 80, 200, 35);
        num.setName("5");
        cp.add(num);

        device = new JLabel[4];

        for (int i = 0; i < 4; i++) {
            device[i] = new JLabel(new ImageIcon("images/" + i + ".png"));
            device[i].setBounds(170 + i * 237, 270, 120, 120);
            device[i].setName(i + "");//相当于加上一个ID，便于写监听器
            cp.add(device[i]);
        }

        clear = new JLabel(new ImageIcon("images/清除选择.png"));
        clear.setBounds(170, 440, 100, 30);
        clear.setName("6");
        cp.add(clear);

        selectAll = new JLabel(new ImageIcon("images/全部选中.png"));
        selectAll.setBounds(890, 440, 100, 30);
        selectAll.setName("7");
        cp.add(selectAll);

        swi = new JLabel(new ImageIcon("images/off.png"));
        swi.setBounds(900, 823, 100, 25);
        swi.setName("8");
        cp.add(swi);

        top = new JLabel(new ImageIcon("images/表头.png"));
        top.setBounds(700, 564, 300, 30);
        cp.add(top);

        tableModel = SQLOperation(REFRESH);
        result = new JTable(tableModel);
        beautifyTable(result);
        result.setBounds(700, 595, 300, 200);
        result.setName("11");
        cp.add(result);

        map = new JLabel(new ImageIcon("maps/1号厅.png"));
        map.setBounds(97, 564, 496, 263);
        map.setName("9");
        cp.add(map);

        bigText = new JTextField();
        bigText.setBounds(0, 0, 1200, 900);
        beautifyTextField(bigText);
        bigText.setEditable(false);
        cp.add(bigText);

        searchText.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                if (searchText.getText().equals("输入所在房间编号"))
                    searchText.setText("");
            }

            @Override
            public void focusLost(FocusEvent e) {
                if (searchText.getText().length() == 0)
                    searchText.setText("输入所在房间编号");
            }
        });

        numText.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                personNum.setVisible(true);
            }

            @Override
            public void focusLost(FocusEvent e) {
                personNum.setVisible(false);
                if (personNum.getSelectedRows().length > 0)
                    numText.setText(personNum.getValueAt(personNum.getSelectedRow(), 0).toString());
            }
        });
        //一次性添加4个监听器
        for (int i = 0; i < 4; i++) {
            device[i].addMouseListener(new TouchListener());
        }
        search.addMouseListener(new TouchListener());
        num.addMouseListener(new TouchListener());
        clear.addMouseListener(new TouchListener());
        selectAll.addMouseListener(new TouchListener());
        swi.addMouseListener(new TouchListener());
        bigGraph.addMouseListener(new TouchListener());
        map.addMouseListener(new TouchListener());
        result.addMouseListener(new TouchListener());
        this.addMouseListener(new TouchListener());

        searchText.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == '\n') {
                    if (!numText.getText().equals("选择与会人数")) {
                        String currentNo = searchText.getText();
                        int flag = 0;
                        int point = 0;
                        //用于检查输入是否符合标准
                        for (int k = 0; k < 2; k++) {
                            for (int i = flag; i < currentNo.length(); i++) {
                                if (currentNo.substring(i, i + 1).equals("-") && currentNo.substring(flag, i).length() > 0) {
                                    point++;
                                    flag = i + 1;
                                }
                            }
                        }
                        //表示第二个-之后有数字
                        if (currentNo.substring(flag).length() > 0 && point == 2) {
                            String SQL = "select position from meeting where code = '" + currentNo + "';";
                            //第一次查询，查找当前所在位置currentPosition
                            SQLSetPosition(SQL);
                            /*
                            * 核心查找方法
                            * */
                            String SQL2 = "select * from meeting where capacity = " + numText.getText()+" and description like '%";
                            for (int i = 0; i <4; i++) {
                                if(deviceSelected[i]){
                                    SQL2+=i+"%";
                                }
                            }
                            SQL2+="';";

                            //第二次查询，查找等于与会人数并满足设备条件的会议室
                            SQLOperation(SQL2);//本来是返回一个表格对象，但是这里先不赋值，而是对meetingRooms进行赋值
                            resultRooms = new ArrayList<>();
                            //foreach循环用来设置和当前位置的距离
                            for (MeetingRoom meetingRoom : meetingRooms) {
                                meetingRoom.setDistance(meetingRoom.getPosition().getDistance(currentPosition));
                            }
                            double min = 100;//初始设置最小值为100
                            int index = 0;
                            for (int i = 0; i < meetingRooms.size(); i++) {
                                if(meetingRooms.get(i).getDistance()<min){
                                    min = meetingRooms.get(i).getDistance();
                                    index = i;
                                }
                            }
                            try{
                                //最佳匹配会议室
                                resultRooms.add(meetingRooms.get(index));
                                //下面是作为备选的一些会议室（距离小于50）
                                for (MeetingRoom meetingRoom : meetingRooms) {
                                    if (meetingRoom.getDistance() < 50&&!resultRooms.contains(meetingRoom)) {
                                        resultRooms.add(meetingRoom);
                                    }
                                }
                            }catch (Exception e1){
                                JOptionPane.showMessageDialog(null,"未找到任何结果");
                            }
                            tableModel = new MyTableModel();
                            for (int i = 1; i <= 3; i++)
                                tableModel.addColumn("");//去掉表头
                            top.setIcon(new ImageIcon("images/表头1.png"));
                            for (MeetingRoom resultRoom : resultRooms) {
                                tableModel.addRow(new Object[]{resultRoom.getName(), resultRoom.getState(),resultRoom.getDistance()});
                            }
                            result.setModel(tableModel);
                            beautifyTable(result);
                        } else {
                            JOptionPane.showMessageDialog(null, "输入的房间编号不正确");
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "输入的与会人数不能为空");
                    }
                }
            }

            @Override
            public void keyPressed(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        });

        this.setVisible(true);
    }

    /**
     * 监听器，复用
     */
    class TouchListener implements MouseListener {

        @Override
        public void mouseClicked(MouseEvent e) {
        }

        @Override
        public void mousePressed(MouseEvent e) {
            int id = Integer.parseInt(e.getComponent().getName());
            //表示选中的是设备
            if (id > -1 && id < 4) {
                if (!deviceSelected[id]) {
                    device[id].setIcon(new ImageIcon("images/" + id + "_选中.png"));
                    deviceSelected[id] = true;
                } else {
                    device[id].setIcon(new ImageIcon("images/" + id + ".png"));
                    deviceSelected[id] = false;
                }
            }
            if (id == 4) {
                searchText.setVisible(true);
                searchText.requestFocus(true);
            }
            if (id == 5) {
                numText.setVisible(true);
                numText.requestFocus(true);
            }
            if (id == 6) {
                for (int i = 0; i < 4; i++) {
                    device[i].setIcon(new ImageIcon("images/" + i + ".png"));
                    deviceSelected[i] = false;
                }
            }
            if (id == 7) {
                for (int i = 0; i < 4; i++) {
                    device[i].setIcon(new ImageIcon("images/" + i + "_选中.png"));
                    deviceSelected[i] = true;
                }
            }
            if (id == 8) {
                if (isSwitchOn) {
                    swi.setIcon(new ImageIcon("images/off.png"));
                    isSwitchOn = false;
                } else {
                    swi.setIcon(new ImageIcon("images/on.png"));
                    isSwitchOn = true;
                }
            }
            if(id==9){
                bigGraph.setVisible(true);
            }
            if(id==10){
                bigGraph.setVisible(false);
            }
            //表示点击总列表
            if(id==11){
                if(result.getValueAt(result.getSelectedRow(),0)!=null){
                    String index = result.getValueAt(result.getSelectedRow(),0).toString().substring(2,3);
                    map.setIcon(new ImageIcon("maps/"+index+"号厅.png"));
                    bigGraph.setIcon(new ImageIcon("bigMaps/"+index+"号厅.png"));
                }
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            int id = Integer.parseInt(e.getComponent().getName());
            switch (id) {
                case 4:
                    search.setIcon(new ImageIcon("images/搜索1.png"));
                    break;
                case 6:
                    clear.setIcon(new ImageIcon("images/清除选择1.png"));
                    break;
                case 7:
                    selectAll.setIcon(new ImageIcon("images/全部选中1.png"));
                    break;
            }
        }

        @Override
        public void mouseExited(MouseEvent e) {
            int id = Integer.parseInt(e.getComponent().getName());
            switch (id) {
                case 4:
                    search.setIcon(new ImageIcon("images/搜索.png"));
                    break;
                case 6:
                    clear.setIcon(new ImageIcon("images/清除选择.png"));
                    break;
                case 7:
                    selectAll.setIcon(new ImageIcon("images/全部选中.png"));
                    break;
            }
        }
    }

    /*
     * ★★★★★★★★执行SQL语句的方法来返回一个新的表格模型★★★★★★★
     * 复用
     * */
    private MyTableModel SQLOperation(String SQL) {

        MyTableModel tableModel1 = new MyTableModel();
        DB dbcon;
        dbcon = new DB();
        try {
            ResultSet rs = dbcon.executeQuery(SQL);
            for (int i = 1; i <= 2; i++)
                tableModel1.addColumn("");//去掉表头

            //用于存放查找到的数据
            meetingRooms = new ArrayList<>();
            while (rs.next()) {
                MeetingRoom meetingRoom = new MeetingRoom();
                meetingRoom.setCode(rs.getString("code"));
                meetingRoom.setName(rs.getString("name"));
                meetingRoom.setCapacity(rs.getInt("capacity"));
                meetingRoom.setDescription(rs.getString("description"));
                meetingRoom.setState(rs.getString("state"));
                meetingRoom.setPosition(rs.getString("position"));
                meetingRooms.add(meetingRoom);
            }
            rs.close();
            for (MeetingRoom meetingRoom : meetingRooms) {
                tableModel1.addRow(new Object[]{meetingRoom.getName(), meetingRoom.getState()});
            }
            dbcon.closeConn();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tableModel1;
    }

    /*
     * 美化一个表格,复用
     * */
    private void beautifyTable(JTable table) {
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, r);//设置居中方式
        table.getTableHeader().setReorderingAllowed(false);
        table.getTableHeader().setResizingAllowed(false);
        table.getTableHeader().setVisible(false);
        table.setRowHeight(33);
        table.setShowGrid(false);//不显示网格线
        table.getColumnModel().getColumn(0).setPreferredWidth(120);
        table.setFont(new Font("黑体", Font.PLAIN, 18));
        table.setPreferredScrollableViewportSize(new Dimension(500, 250));
    }

    /*
     * ★★★★★★★★执行SQL语句的方法来设置一个当前位置★★★★★★★
     * 复用
     * */
    private void SQLSetPosition(String SQL) {
        DB dbcon;
        dbcon = new DB();
        try {
            ResultSet rs = dbcon.executeQuery(SQL);
            rs.last();
            currentPosition = new Position(rs.getString(1));//获得结果集
            rs.close();
            dbcon.closeConn();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 文本框美化方法复用
     * */
    private void beautifyTextField(JTextField jTextfield) {
        jTextfield.setOpaque(false);
        jTextfield.setHorizontalAlignment(JTextField.CENTER);
        jTextfield.setForeground(Color.white);
        jTextfield.setFont(new Font("黑体", Font.PLAIN, 20));
        jTextfield.setBorder(new LineBorder(null, 0));
    }

    public static void main(String[] args) {
        new meetingJFrame();
    }
}
